using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using net_work.Common.Result;
using net_work.Data.DTO.System;
using net_work.IService.System;

namespace net_work.Controllers.System;

[Route("api/[controller]")]
[ApiController]
public class FileController(ILogger<FileController> logger, IFileService fileService) : ControllerBase
{
    /// <summary>
    /// 获取文件列表
    /// </summary>
    /// <param name="fileUseAddRequest">业务信息</param>
    /// <returns>文件列表</returns>
    [HttpPost("list")]
    [Authorize]
    public async Task<IActionResult> GetFileList([FromBody] FileUseAddRequest fileUseAddRequest)
    {
        logger.LogInformation("获取文件列表");
        return AjaxResult.Success(await fileService.GetFileList(fileUseAddRequest));
    }

    /// <summary>
    /// 上传文件
    /// </summary>
    /// <param name="file">文件</param>
    /// <param name="fileUseAddRequest">业务信息</param>
    /// <returns>操作结果</returns>
    [HttpPost("upload")]
    [Authorize]
    public async Task<IActionResult> UploadFile(IFormFile file, [FromForm] FileUseAddRequest fileUseAddRequest)
    {
        logger.LogInformation("上传文件");
        if (file.Length <= 0)
        {
            return AjaxResult.Error("文件无效");
        }

        return await fileService.UploadFile(file, fileUseAddRequest) > 0
            ? AjaxResult.Success("上传成功")
            : AjaxResult.Error("上传失败");
    }

    /// <summary>
    /// 删除文件
    /// </summary>
    /// <param name="ids">文件ID列表</param>
    /// <returns>操作结果</returns>
    [HttpPost("delete")]
    [Authorize]
    public async Task<IActionResult> DeleteFiles([FromBody] List<long> ids)
    {
        logger.LogInformation("删除文件");
        return await fileService.DeleteFiles(ids) > 0
            ? AjaxResult.Success("删除成功")
            : AjaxResult.Error("删除失败");
    }

    /// <summary>
    /// 下载文件
    /// </summary>
    /// <param name="myFileId">文件ID</param>
    /// <returns>文件</returns>
    [HttpGet("download")]
    [Authorize]
    public async Task<IActionResult> DownloadStream([FromQuery] long myFileId)
    {
        try
        {
            logger.LogInformation("下载文件");
            var fileResult = await fileService.DownloadStream(myFileId);

            if (fileResult == null)
            {
                return NotFound("File not found");
            }

            return fileResult;
        }
        catch (FileNotFoundException ex)
        {
            return NotFound(ex.Message);
        }
        catch (Exception ex)
        {
            logger.LogError("File stream download failed{}", ex);
            return StatusCode(500, "Internal server error");
        }
    }
}